package com.kuang.handler;

import com.kuang.common.UserThreadLocal;
import com.kuang.common.anno.IgnoreToken;
import com.kuang.common.exception.ValidationException;
import com.kuang.service.product.UserService;
import com.kuang.utils.MD5Util;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author xuke
 */
@Log4j2
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Value("${spring.profiles.active}")
    private String profiles;


    public static String getParam(HttpServletRequest request, String filedName) {
        String param = request.getParameter(filedName);
        if (StringUtils.isEmpty(param)) {
            param = request.getHeader(filedName);
        }

        return param;
    }

    /**
     * 校验token
     *
     * @param request
     * @param response
     * @param object
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
    /*    if (StringUtils.isNotEmpty(profiles) && profiles.equalsIgnoreCase("dev")) {
            return true;
        }*/
        // 从 http 请求头获取请求接口
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(IgnoreToken.class)) {
            IgnoreToken loginToken = method.getAnnotation(IgnoreToken.class);
            if (loginToken.required()) {
                //检查是否有IgnoreToken注释，有则跳过认证
                String token = getParam(request, "token");
                String userid = getParam(request, "userid");
                log.info("token是：{}", token);
                if (StringUtils.isEmpty(token)) {
                    log.info("token请重新登录");
                    throw new ValidationException(300, "token不允许为空，请重新登录!!!");
                }

                // 全局忽略
                String sign = MD5Util.md5slat("31fd29656c0442b26a237b8de6834aad"+userid);
                if (!sign.equalsIgnoreCase(token)) {
                    log.info("tokenvalue不正确{}", token);
                    throw new ValidationException(300, "token签名不对，请重新登录!!!");
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //销毁
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁
        UserThreadLocal.remove();
    }
}
